<?php
namespace app\common\libs;


/**
 * @author : SN
 * @time   : 2020/3/30 16:19
 * @des    : curl工具类
 */
class Http
{

    public static $GET = 'GET';
    public static $POST = 'POST';
    public static $PUT = 'PUT';
    public static $PATCH = 'PATCH';
    public static $DELETE = 'DELETE';


    /**
     * @author : SN
     * @time   : 2020/3/30 16:20
     * @des    : application/json格式数据
     * @param $url
     * @param string $method
     * @param array $data
     * @param array $headers
     * @return bool|string
     */
    public static function http_json($url, $method='GET', $data=[], $headers=[]){
        if ($headers == null || !in_array("Content-type: application/json", $headers)){
            $headers[] = "Content-type: application/json";
        }
        if(is_array($data)){
            $data = json_encode($data);
        }
        return self::request($url, $method, $data, $headers);
    }


    public static function request($url, $method='GET', $data=null, $headers=null){

        if (!$url){
            abort(400, "request url is null");
        }

        $ch = curl_init($url);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10); //超时时间
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回，而不是直接输出


        switch ($method){
            case self::$GET:
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case self::$POST:
                curl_setopt($ch, CURLOPT_POST,true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case self::$PATCH:
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, self::$PATCH);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case self::$PUT:
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST,self::$PUT); //设置请求方式
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case self::$DELETE:
                curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, self::$DELETE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
        }

        if ($headers){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        $result = curl_exec($ch);//获得返回值
        $error = curl_error($ch);
        curl_close($ch);
        if ($error){
            abort(500, $error);
        }
        return $result;
    }







}